﻿using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Terminal;
using com.nm.Helper;
using george.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TerminalAPI.models;
using System.Data.Entity.Validation;


namespace TerminalAPI
{
    [Description("店铺基本信息")]
    public class ShopHandler : BaseHandler
    {
        [MustLogin]
        [Description("店铺基本信息列表")]
        [ReturnType(typeof(PaperData<ShopModel.ListModel>))]
        public ApiResult GetList(
           [ParamDescription("店铺编号")] string ShopCode = "",
            [ParamDescription("年份")] string Year = "",
            [ParamDescription("季节")] string Season = "",
            [ParamDescription("陈列级别")] string Leavel = "",
            [ParamDescription("营业状态")] string BusinessStatus = "",
            [ParamDescription("页码")]int Page = 1,
            [ParamDescription("页数")]int Size = 10)
        {
            var dc = new TerminalEntities();
            var query = (from shop in dc.Tm_Shop
                         join hkShop in dc.hk_vm_shop on shop.ShopCode equals hkShop.shopcode
                         select new
                         {
                             shop.IsRemove,
                             shop.SID,
                             shop.Year,
                             shop.Season,
                             shop.ShopCode,
                             //店铺陈列级别使用tm_shop表字段Levels
                             shop.Levels,
                             shop.ModifyDate,
                             shop.Operator,
                             shop.CreateDate,
                             //店铺销售级别使用tm_shop表字段ShopLevels
                             shop.ShopLevels,
                             shop.Province,
                             shop.City,
                             shop.SubordinateArea,
                             shop.BusinessStatus,
                             shop.OpeningDate,
                             shop.CloseDate,
                             shop.SuspensionDate,
                             shop.ResumptionDate,
                             shop.BusinessModel,
                             shop.BusinessArea,
                             shop.WarehouseArea,
                             shop.LogisticsTimeDay,
                             shop.StoreImage,
                             shop.BusinessDistrictLevel,
                             shop.OperatingFormat,
                             shop.BusinessDistrictType,
                             shop.ConsumerGroupsOfStudent,
                             shop.ConsumerGroupsOfBlueCollar,
                             shop.ConsumerGroupsOfWhiteCollar,
                             shop.ConsumerGroupsOfVisitor,
                             shop.AgeGroup18To22,
                             shop.AgeGroup23To27,
                             shop.AgeGroup28To34,
                             shop.AgeGroup35To40,
                             shop.LeisureSeries,
                             shop.EliteSeries,
                             shop.CreativeSeries,
                             shop.StyleNumber,
                             shop.FixedFlow,
                             shop.SpecialNote,
                             hkShop.Area,
                             hkShop.shopname,
                         });
            if (!string.IsNullOrWhiteSpace(ShopCode))
                query = query.Where(t => t.ShopCode.Contains(ShopCode));
            if (!string.IsNullOrWhiteSpace(Year))
                query = query.Where(t => t.Year.Contains(Year));
            if (!string.IsNullOrWhiteSpace(Season))
                query = query.Where(t => t.Season.Contains(Season));
            if (!string.IsNullOrWhiteSpace(Leavel))
                query = query.Where(t => t.Levels.Contains(Leavel));
            if (!string.IsNullOrWhiteSpace(BusinessStatus))
            {
                query = query.Where(r => r.BusinessStatus == BusinessStatus);
            }

            var result = PaperData<ShopModel.ListModelNew>.Create(query.Count(), Size, Page);
            result.Items = query.OrderByDescending(t => t.CreateDate).Skip(result.Skip)
                .Take(result.Limt).ToList()
                .Select(o => new ShopModel.ListModelNew
                {
                    Area = o.Area,
                    ShopLevels = o.ShopLevels,
                    // Image = ImageHelper.GetResolveImageUrl(o.ShopCode, "shop", "http"),
                    Image = "",

                    SID = o.SID,
                    Year = o.Year,
                    Season = o.Season,
                    ShopCode = o.ShopCode,
                    Levels = o.Levels,
                    ModifyDate = (DateTime)o.ModifyDate,
                    IsRemove = o.IsRemove,
                    Operator = o.Operator,
                    CreateDate = (DateTime)o.CreateDate,
                    ShopName = o.shopname,
                    Province = o.Province,
                    City = o.City,
                    SubordinateArea = o.SubordinateArea,
                    BusinessStatus = o.BusinessStatus,
                    OpeningDate = o.OpeningDate,
                    CloseDate = o.CloseDate,
                    SuspensionDate = o.SuspensionDate,
                    ResumptionDate = o.ResumptionDate,

                    //OpeningDate = string.IsNullOrWhiteSpace(o.OpeningDate)?"": Convert.ToDateTime(o.OpeningDate).ToString("yyyy-MM-dd"),
                    //CloseDate = string.IsNullOrWhiteSpace(o.CloseDate) ? "" : Convert.ToDateTime(o.CloseDate).ToString("yyyy-MM-dd"), 
                    //SuspensionDate = string.IsNullOrWhiteSpace(o.SuspensionDate) ? "" : Convert.ToDateTime(o.SuspensionDate).ToString("yyyy-MM-dd"),
                    //ResumptionDate = string.IsNullOrWhiteSpace(o.ResumptionDate) ? "" : Convert.ToDateTime(o.ResumptionDate).ToString("yyyy-MM-dd"),
                    BusinessModel = o.BusinessModel,
                    BusinessArea = o.BusinessArea,
                    WarehouseArea = o.WarehouseArea,
                    LogisticsTimeDay = o.LogisticsTimeDay,
                    StoreImage = o.StoreImage,
                    BusinessDistrictLevel = string.IsNullOrWhiteSpace(o.BusinessDistrictLevel) ? "" : o.BusinessDistrictLevel,
                    OperatingFormat = o.OperatingFormat,
                    BusinessDistrictType = o.BusinessDistrictType,
                    ConsumerGroupsOfStudent = o.ConsumerGroupsOfStudent,
                    ConsumerGroupsOfBlueCollar = o.ConsumerGroupsOfBlueCollar,
                    ConsumerGroupsOfWhiteCollar = o.ConsumerGroupsOfWhiteCollar,
                    ConsumerGroupsOfVisitor = o.ConsumerGroupsOfVisitor,
                    AgeGroup18To22 = o.AgeGroup18To22 == null ? 0 : o.AgeGroup18To22.Value,
                    AgeGroup23To27 = o.AgeGroup23To27 == null ? 0 : o.AgeGroup23To27.Value,
                    AgeGroup28To34 = o.AgeGroup28To34 == null ? 0 : o.AgeGroup28To34.Value,
                    AgeGroup35To40 = o.AgeGroup35To40 == null ? 0 : o.AgeGroup35To40.Value,
                    LeisureSeries = o.LeisureSeries == null ? 0 : o.LeisureSeries.Value,
                    EliteSeries = o.EliteSeries == null ? 0 : o.EliteSeries.Value,
                    CreativeSeries = o.CreativeSeries == null ? 0 : o.CreativeSeries.Value,
                    StyleNumber = string.IsNullOrWhiteSpace(o.StyleNumber) ? "" : o.StyleNumber,
                    FixedFlow = string.IsNullOrWhiteSpace(o.FixedFlow) ? "" : o.FixedFlow,
                    SpecialNote = string.IsNullOrWhiteSpace(o.SpecialNote) ? "" : o.SpecialNote,
                }).ToList();
            return Success(result);
        }

        [MustLogin]
        [Description("获取所有店铺")]
        [ReturnType(typeof(IList<ShopModel.HkShopList>))]
        public ApiResult GetShopBaseInfo(
           [ParamDescription("关键字")] string Keys = "",
           [ParamDescription("是否获取全部列表")] string GetAllList = "True")
        {

            var dc = new TerminalEntities();
            /*
            var query = (from shop in dc.hk_vm_shop
                         where shop.shopcode.Contains(Keys) || shop.shopname.Contains(Keys)
                         select shop);
            */
            string strSql = $@"
                select top 8 
                hk.shopcode as ShopCode,
                hk.shopname as ShopName
                    from hk_vm_shop hk
                left
                    join Tm_Shop tm
                on hk.shopcode = tm.ShopCode 
                where 1=1 
                {(string.IsNullOrWhiteSpace(Keys) ? "" : $" and (hk.shopcode like '%{Keys}%' or hk.shopname like '%{Keys}%') ")}
                ";
            if (GetAllList == "False")
            {
                strSql += " and tm.ShopCode is null";
            }
            var shopList = dc.Database.SqlQuery<ShopModel.HkShopList>(strSql);
            return Success(shopList);
        }

        [MustLogin]
        [Description("店铺基本信息明细")]
        [ReturnType(typeof(ShopModel.ListModelNew))]
        public ApiResult GetID(
            [ParamDescription("ID")] int ID)
        {
            var dc = new TerminalEntities();
            var query = (from shop in dc.Tm_Shop
                         join hkShop in dc.hk_vm_shop on shop.ShopCode equals hkShop.shopcode
                         where shop.SID == ID
                         select new
                         {
                             shop.IsRemove,
                             shop.SID,
                             shop.Year,
                             shop.Season,
                             shop.ShopCode,
                             shop.Levels,
                             shop.ModifyDate,
                             shop.Operator,
                             shop.CreateDate,
                             shop.ShopLevels,
                             hkShop.shopname,
                             shop.Province,
                             shop.City,
                             shop.SubordinateArea,
                             shop.BusinessStatus,
                             shop.OpeningDate,
                             shop.CloseDate,
                             shop.SuspensionDate,
                             shop.ResumptionDate,
                             shop.BusinessModel,
                             shop.BusinessArea,
                             shop.WarehouseArea,
                             shop.LogisticsTimeDay,
                             shop.StoreImage,
                             shop.BusinessDistrictLevel,
                             shop.OperatingFormat,
                             shop.BusinessDistrictType,
                             shop.ConsumerGroupsOfStudent,
                             shop.ConsumerGroupsOfBlueCollar,
                             shop.ConsumerGroupsOfWhiteCollar,
                             shop.ConsumerGroupsOfVisitor,
                             shop.AgeGroup18To22,
                             shop.AgeGroup23To27,
                             shop.AgeGroup28To34,
                             shop.AgeGroup35To40,
                             shop.LeisureSeries,
                             shop.EliteSeries,
                             shop.CreativeSeries,
                             shop.StyleNumber,
                             shop.FixedFlow,
                             shop.SpecialNote,
                         });
            var result = query.Select(o => new ShopModel.ListModelNew
            {
                SID = o.SID,
                Year = o.Year,
                Season = o.Season,
                ShopCode = o.ShopCode,
                Levels = o.Levels.Trim(),
                ModifyDate = (DateTime)o.ModifyDate,
                IsRemove = o.IsRemove,
                Operator = o.Operator,
                CreateDate = (DateTime)o.CreateDate,
                ShopLevels = o.ShopLevels,
                ShopName = o.shopname,
                Province = o.Province,
                City = o.City,
                SubordinateArea = o.SubordinateArea,
                BusinessStatus = o.BusinessStatus,
                OpeningDate = o.OpeningDate,
                CloseDate = o.CloseDate,
                SuspensionDate = o.SuspensionDate,
                ResumptionDate = o.ResumptionDate,
                BusinessModel = o.BusinessModel,
                BusinessArea = o.BusinessArea,
                WarehouseArea = o.WarehouseArea,
                LogisticsTimeDay = o.LogisticsTimeDay,
                StoreImage = o.StoreImage,
                BusinessDistrictLevel = o.BusinessDistrictLevel,
                OperatingFormat = o.OperatingFormat,
                BusinessDistrictType = o.BusinessDistrictType,
                ConsumerGroupsOfStudent = o.ConsumerGroupsOfStudent,
                ConsumerGroupsOfBlueCollar = o.ConsumerGroupsOfBlueCollar,
                ConsumerGroupsOfWhiteCollar = o.ConsumerGroupsOfWhiteCollar,
                ConsumerGroupsOfVisitor = o.ConsumerGroupsOfVisitor,
                AgeGroup18To22 = o.AgeGroup18To22 == null ? 0 : o.AgeGroup18To22.Value,
                AgeGroup23To27 = o.AgeGroup23To27 == null ? 0 : o.AgeGroup23To27.Value,
                AgeGroup28To34 = o.AgeGroup28To34 == null ? 0 : o.AgeGroup28To34.Value,
                AgeGroup35To40 = o.AgeGroup35To40 == null ? 0 : o.AgeGroup35To40.Value,
                LeisureSeries = o.LeisureSeries == null ? 0 : o.LeisureSeries.Value,
                EliteSeries = o.EliteSeries == null ? 0 : o.EliteSeries.Value,
                CreativeSeries = o.CreativeSeries == null ? 0 : o.CreativeSeries.Value,
                StyleNumber = o.StyleNumber,
                FixedFlow = o.FixedFlow,
                SpecialNote = o.SpecialNote,
            }).FirstOrDefault();
            return Success(result);
        }
        /*
        [JsonType]
        [MustLogin]
        [Description("新增店铺基本信息")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Create([ParamDescription("输入参数")]ShopModel.CreateModel param)
        {
            if (string.IsNullOrWhiteSpace(param.ShopCode)) return Error("店铺编号不能为空");
            if (string.IsNullOrWhiteSpace(param.Year)) return Error("年份不能为空");
            if (string.IsNullOrWhiteSpace(param.Season)) return Error("季节不能为空");
            if (string.IsNullOrWhiteSpace(param.Levels)) return Error("店铺陈列级别不能为空");
            var dc = new TerminalEntities();
            if (dc.Tm_Shop.Any(t => t.ShopCode == param.ShopCode)) return Error($"店铺编号【{param.ShopCode}】已存在");
            var shop = new Tm_Shop
            {
                CreateDate = DateTime.Now,
                IsRemove = false,
                Levels = param.Levels,
                ModifyDate = DateTime.Now,
                Operator = this.UserId,
                Season = param.Season,
                ShopCode = param.ShopCode,
                Year = param.Year
            };
            dc.Tm_Shop.Add(shop);
            try
            {
                dc.SaveChanges();
            }
            catch(Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }
        */

        [JsonType]
        [MustLogin]
        [Description("新增店铺基本信息")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Create([ParamDescription("输入参数")]ShopModel.CreateModelNew param)
        {
            if (string.IsNullOrWhiteSpace(param.ShopCode)) return Error("店铺编号不能为空");
            if (string.IsNullOrWhiteSpace(param.ShopName)) return Error("店铺名称不能为空");
            if (string.IsNullOrWhiteSpace(param.BusinessStatus)) return Error("营业状态不能为空");
            if (string.IsNullOrWhiteSpace(param.WarehouseArea)) return Error("仓库面积级别不能为空");
            if (string.IsNullOrWhiteSpace(param.LogisticsTimeDay)) return Error("物流时间天不能为空");
            if (string.IsNullOrWhiteSpace(param.StoreImage)) return Error("店铺形象不能为空");
            if (string.IsNullOrWhiteSpace(param.OperatingFormat)) return Error("经营业态不能为空");
            if (string.IsNullOrWhiteSpace(param.BusinessArea)) return Error("营业面积不能为空");
            if (string.IsNullOrWhiteSpace(param.ShopLevels)) return Error("店铺销售级别不能为空");
            if (string.IsNullOrWhiteSpace(param.Levels)) return Error("陈列级别不能为空");
            if (string.IsNullOrWhiteSpace(param.BusinessModel)) return Error("经营模式不能为空");
            if (string.IsNullOrWhiteSpace(param.Levels)) return Error("隶属运营区域不能为空");
            var dc = new TerminalEntities();
            if (dc.Tm_Shop.Any(t => t.ShopCode == param.ShopCode)) return Error($"店铺编号【{param.ShopCode}】已存在");
            var shop = new Tm_Shop
            {
                CreateDate = DateTime.Now,
                IsRemove = false,
                Levels = param.Levels,
                ModifyDate = DateTime.Now,
                Operator = this.UserId,
                Season = param.Season,
                ShopCode = param.ShopCode,
                Year = param.Year,
                ShopName = param.ShopName,
                ShopLevels = param.ShopLevels,
                Province = param.Province,
                City = param.City,
                SubordinateArea = param.SubordinateArea,
                BusinessStatus = param.BusinessStatus,
                OpeningDate = param.OpeningDate,
                CloseDate = param.CloseDate,
                SuspensionDate = param.SuspensionDate,
                ResumptionDate = param.ResumptionDate,
                BusinessModel = param.BusinessModel,
                BusinessArea = param.BusinessArea,
                WarehouseArea = param.WarehouseArea,
                LogisticsTimeDay = param.LogisticsTimeDay,
                StoreImage = param.StoreImage,
                BusinessDistrictLevel = param.BusinessDistrictLevel,
                OperatingFormat = param.OperatingFormat,
                BusinessDistrictType = param.BusinessDistrictType,
                ConsumerGroupsOfStudent = param.ConsumerGroupsOfStudent,
                ConsumerGroupsOfBlueCollar = param.ConsumerGroupsOfBlueCollar,
                ConsumerGroupsOfWhiteCollar = param.ConsumerGroupsOfWhiteCollar,
                ConsumerGroupsOfVisitor = param.ConsumerGroupsOfVisitor,
                AgeGroup18To22 = param.AgeGroup18To22,
                AgeGroup23To27 = param.AgeGroup23To27,
                AgeGroup28To34 = param.AgeGroup28To34,
                AgeGroup35To40 = param.AgeGroup35To40,
                LeisureSeries = param.LeisureSeries,
                EliteSeries = param.EliteSeries,
                CreativeSeries = param.CreativeSeries,
                StyleNumber = param.StyleNumber,
                FixedFlow = param.FixedFlow,
                SpecialNote = param.SpecialNote,
            };
            dc.Tm_Shop.Add(shop);
            try
            {
                dc.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [JsonType]
        [MustLogin]
        [Description("编辑店铺基本信息")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Modify([ParamDescription("输入参数")]ShopModel.ModifyModelNew param)
        {
            if (string.IsNullOrWhiteSpace(param.ShopCode)) return Error("店铺编号不能为空");
            if (string.IsNullOrWhiteSpace(param.ShopName)) return Error("店铺名称不能为空");
            if (string.IsNullOrWhiteSpace(param.BusinessStatus)) return Error("营业状态不能为空");
            if (string.IsNullOrWhiteSpace(param.WarehouseArea)) return Error("仓库面积级别不能为空");
            if (string.IsNullOrWhiteSpace(param.LogisticsTimeDay)) return Error("物流时间天不能为空");
            if (string.IsNullOrWhiteSpace(param.StoreImage)) return Error("店铺形象不能为空");
            if (string.IsNullOrWhiteSpace(param.OperatingFormat)) return Error("经营业态不能为空");
            if (string.IsNullOrWhiteSpace(param.BusinessArea)) return Error("营业面积不能为空");
            if (string.IsNullOrWhiteSpace(param.ShopLevels)) return Error("店铺销售级别不能为空");
            if (string.IsNullOrWhiteSpace(param.Levels)) return Error("陈列级别不能为空");
            if (string.IsNullOrWhiteSpace(param.BusinessModel)) return Error("经营模式不能为空");
            if (string.IsNullOrWhiteSpace(param.Levels)) return Error("隶属运营区域不能为空");
            var dc = new TerminalEntities();
            if (dc.Tm_Shop.Any(t => t.ShopCode == param.ShopCode && t.SID != param.SID)) return Error($"店铺编号【{param.ShopCode}】已存在");
            var query = dc.Tm_Shop.FirstOrDefault(t => t.SID == param.SID);
            if (query == null) return Error("无数据");

            query.ModifyDate = DateTime.Now;
            query.Operator = this.UserId;
            query.Year = param.Year;
            query.Season = param.Season;
            query.ShopCode = param.ShopCode;
            query.Levels = param.Levels;
            query.ShopLevels = param.ShopLevels;
            query.ShopName = param.ShopName;
            query.Province = param.Province;
            query.City = param.City;
            query.SubordinateArea = param.SubordinateArea;
            query.BusinessStatus = param.BusinessStatus;
            query.OpeningDate = param.OpeningDate;
            query.CloseDate = param.CloseDate;
            query.SuspensionDate = param.SuspensionDate;
            query.ResumptionDate = param.ResumptionDate;
            query.BusinessModel = param.BusinessModel;
            query.BusinessArea = param.BusinessArea;
            query.WarehouseArea = param.WarehouseArea;
            query.LogisticsTimeDay = param.LogisticsTimeDay;
            query.StoreImage = param.StoreImage;
            query.BusinessDistrictLevel = param.BusinessDistrictLevel;
            query.OperatingFormat = param.OperatingFormat;
            query.BusinessDistrictType = param.BusinessDistrictType;
            query.ConsumerGroupsOfStudent = param.ConsumerGroupsOfStudent;
            query.ConsumerGroupsOfBlueCollar = param.ConsumerGroupsOfBlueCollar;
            query.ConsumerGroupsOfWhiteCollar = param.ConsumerGroupsOfWhiteCollar;
            query.ConsumerGroupsOfVisitor = param.ConsumerGroupsOfVisitor;
            query.AgeGroup18To22 = param.AgeGroup18To22;
            query.AgeGroup23To27 = param.AgeGroup23To27;
            query.AgeGroup28To34 = param.AgeGroup28To34;
            query.AgeGroup35To40 = param.AgeGroup35To40;
            query.LeisureSeries = param.LeisureSeries;
            query.EliteSeries = param.EliteSeries;
            query.CreativeSeries = param.CreativeSeries;
            query.StyleNumber = param.StyleNumber;
            query.FixedFlow = param.FixedFlow;
            query.SpecialNote = param.SpecialNote;
            try
            {

                dc.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [MustLogin]
        [ReturnType(typeof(int), "0-成功")]
        [Description("删除店铺基本信息")]
        public ApiResult Remove([ParamDescription("ID")]int ID)
        {
            var dc = new TerminalEntities();
            var query = dc.Tm_Shop.FirstOrDefault(t => t.SID == ID);
            if (query == null) return Error("无数据");
            query.IsRemove = true;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

    }
}
